"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/12/28
 */
import * as React from 'react'
import {autoSize, commonProps, commonStyles} from "../../assets/styles/common";
import Colors from "../../assets/styles/Colors";
import NavBackButton from "../../component/BackButton";
import NavRightButton from "../../component/RightButton";
import MyText from "../../component/MyText";
import MyIcon from "../../component/icon";
import T from "../../utils/T";
import {AddHobbyOrSkillPageProps, AddHobbyOrSkillPageState} from "../../interface/router";
import Line from "../../component/Line";

const {View, StyleSheet, TouchableOpacity, TextInput, FlatList} = require('react-native');
const {connect} = require('react-redux');
const NavigationBar = require('react-native-navbar').default;
const {Actions} = require("react-native-router-flux");
const {SwipeListView} = require('react-native-swipe-list-view');
const Collapsible = require('react-native-collapsible').default;

class AddHobbyOrSkillPage extends React.Component<AddHobbyOrSkillPageProps, AddHobbyOrSkillPageState> {

    type: number;

    constructor(props: AddHobbyOrSkillPageProps, context: any,) {
        super(props, context);
        this.state = {
            data: props.data,
            collapsed: true,
            selectedIds: props.data.map(i => i.id)
        };
        this.type = props.title === 'Skills' ? 1 : 2;
    }

    componentDidMount(): void {
        this.onRefresh();
    }


    onPressDone = () => {
        this.props.callBack && this.props.callBack(this.state.data);
        Actions.pop()
    };
    onRefresh = () => {
        this.props.dispatch({
            type: 'user/fetchTags',
            payload: {
                pi: 1,
                ps: 50,
                type: this.type
            }
        })
    };


    getData = () => {
        let data = [];
        if (this.props.title === 'Skills') {
            if (this.props.user.skillList) {
                data = this.props.user.skillList.content
            }
        }
        if (this.props.title === 'Hobbies') {
            if (this.props.user.hobbyList) {
                data = this.props.user.hobbyList.content
            }
        }
        return data;
    };


    onSelectedItem = (i: hobbyItem) => {
        let selectedIds = this.state.selectedIds || [];
        const index = selectedIds.indexOf(i.id);
        if (index === -1) {
            selectedIds.push(i.id);
        } else {
            selectedIds.splice(index, 1);
        }


        let data = [];
        const allData = this.getData;
        selectedIds.map(i => {
            allData().map((ii: hobbyItem) => {
                if (i === ii.id) {
                    data.push(ii);
                }
            })
        });
        this.setState({selectedIds, data});
    };
    changeCollapsed = () => {
        this.setState({collapsed: !this.state.collapsed})
    };
    closeRow = (rowMap, rowKey) => {
        if (rowMap[rowKey]) {
            // console.log(1);
            rowMap[rowKey].closeRow();
        } else {
            // console.log(2);
        }

    };
    onDeletePress = (rowMap, rowKey) => {
        this.closeRow(rowMap, rowKey);
        let index = this.state.selectedIds.indexOf(rowKey);
        index !== -1 && this.state.selectedIds.splice(index, 1);
        let selectedIds = this.state.selectedIds;
        let data = [];
        this.state.data.map((i: hobbyItem) => {
            if (i.id !== rowKey) {
                data.push(i)
            }
        });
        this.setState({data, selectedIds});
    };

    renderItem = (d, r) => {
        const item: hobbyItem = d.item;
        return (
            <View style={styles.rowFront}>
                <MyText color={Colors.Title} fontSize={15}>{item.text}</MyText>
            </View>
        )
    };
    renderHiddenItem = (data, rowMap) => {
        return (
            <View style={styles.rowBack}>
                <TouchableOpacity style={styles.deleteBtn}
                                  onPress={this.onDeletePress.bind(this, rowMap, data.item.id)}>
                    <MyText color={Colors.White} fontSize={16}>删除</MyText>
                </TouchableOpacity>
            </View>
        )
    };

    renderItem1 = (i) => {
        const isSelected = this.state.selectedIds ? this.state.selectedIds.indexOf(i.item.id) !== -1 : false;
        return (
            <TouchableOpacity style={[styles.rowFront, {height: 40}]} onPress={this.onSelectedItem.bind(this, i.item)}>
                <View style={[commonStyles.flexRow, {alignItems: 'center'}]}>
                    <View style={[commonStyles.flex1]}>
                        <MyText color={isSelected ? Colors.Active : Colors.Title}>{i.item.text}</MyText>
                    </View>
                    {isSelected && <MyIcon name={'icon-gou'} color={Colors.Active} size={20}/>}
                </View>
            </TouchableOpacity>
        )
    };

    render() {
        return (
            <View style={[commonStyles.container, {backgroundColor: Colors.White}]}>
                <NavigationBar {...commonProps.navBar}
                               leftButton={<NavBackButton/>}
                               rightButton={<NavRightButton onPress={this.onPressDone}>
                                   <MyText color={Colors.Active}>{T('Done')}</MyText>
                               </NavRightButton>}
                               title={{title: `编辑 ${this.props.title}`, tintColor: '#fff'}}
                />
                <TouchableOpacity style={styles.inputContainer} onPress={this.changeCollapsed}>
                    <MyText>选择您的技能或兴趣</MyText>
                    {/*<View style={[commonStyles.flex1]}>*/}
                    {/*<TextInput placeholder={T(`add your ${this.props.title}`) + '...'}/>*/}
                    {/*</View>*/}

                    {/*<TouchableOpacity style={styles.addBtn}>*/}
                    {/*<MyIcon name={'icon-jia1'} color={Colors.SubTitle} size={20}/>*/}
                    {/*</TouchableOpacity>*/}
                </TouchableOpacity>


                <Collapsible collapsed={this.state.collapsed} align="center">
                    <View>
                        <FlatList data={this.getData()}
                                  onRefresh={this.onRefresh}
                                  refreshing={this.props.user.loading}
                                  extraData={this.state}
                                  keyExtractor={(d) => d.id}
                                  renderItem={this.renderItem1}/>
                    </View>
                </Collapsible>

                <Line color={Colors.Background} height={20}/>

                <SwipeListView useFlatList={true}
                               disableRightSwipe
                               data={this.state.data}
                               closeOnRowBeginSwipe={true}
                               renderItem={this.renderItem}
                               leftOpenValue={0}
                               rightOpenValue={-autoSize(75)}
                               keyExtractor={(d) => d.id}
                               previewRowKey={null}
                               renderHiddenItem={this.renderHiddenItem}
                />

            </View>
        );
    }
}


const
    styles = StyleSheet.create({
        rowFront: {
            display: 'flex',
            justifyContent: 'center',
            padding: 10,
            borderBottomWidth: 1,
            borderBottomColor: Colors.Separate,
            backgroundColor: Colors.White
        },
        rowBack: {
            alignItems: 'center',
            backgroundColor: Colors.Red,
            flex: 1,
            flexDirection: 'row',
            justifyContent: 'flex-end',
            paddingLeft: 15,
        },
        deleteBtn: {
            width: autoSize(75),

            height: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
        },
        inputContainer: {
            display: 'flex',
            alignItems: 'center',
            padding: 10,
            borderBottomWidth: 1,
            borderBottomColor: Colors.Separate,
            backgroundColor: Colors.White,
            height: autoSize(50),
            flexDirection: 'row'
        },
        addBtn: {
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
            width: autoSize(50)
        }
    });

export default connect(
    ({auth, user}) => ({auth, user})
)(AddHobbyOrSkillPage);